import { ref, reactive, computed } from 'vue'
import { getDataByPage, postUpdateRecord } from '@/api/3D-Generator'
import { ElMessage } from 'element-plus'
import { convertToProxyUrl } from '@/util/replaceUrl'
import request from '@/util/request'

// 格式优先级配置 - GLB为最高优先级
const MODEL_FORMAT_PRIORITY = {
    'GLB': 10,     // 最高优先级
    'GLTF': 9,     // 次高优先级
    'OBJ': 8,      // 第三优先级
    'FBX': 7,      // 第四优先级
    'STL': 6,      // 第五优先级
    'USDZ': 5,     // 第六优先级
    'ZIP': 4,      // 较低优先级（可能包含OBJ）
    'PLY': 3,      // 更低优先级
    'DAE': 2,      // 很低优先级
    'X3D': 1       // 最低优先级
}

/**
 * 3D模型历史记录管理Hook
 * 负责历史记录的查询、分页、筛选、排序等功能，以及并发轮询处理中的任务
 */
export function useModelHistory() {
    // ========== 原有响应式数据 ==========
    const historyList = ref([])
    const historyState = reactive({
        loading: false,
        currentPage: 1,
        pageSize: 20,
        total: 0,
        hasMore: true,
        error: null
    })
    const filterState = reactive({
        type: 'all',
        status: 'all',
        sortBy: 'time_desc'
    })

    // ========== 新增：并发轮询状态管理 ==========
    const pollingState = reactive({
        activePolls: new Map(), // 活跃的轮询任务 key: taskId, value: 轮询信息
        pollingConfig: {
            interval: 30000,        // 轮询间隔 30秒
            maxAttempts: 180,       // 最大尝试次数 90分钟
            batchUpdateDelay: 3000  // 批量更新延迟 3秒
        },
        pendingUpdates: new Set(), // 待更新的任务集合
        updateTimer: null          // 批量更新定时器
    })

    // ========== 格式处理辅助函数 ==========

    /**
     * 从文件URL中提取格式
     * @param {string} url - 文件URL
     * @returns {string} 格式名称（大写）
     */
    const extractFormatFromUrl = (url) => {
        if (!url || typeof url !== 'string') return 'UNKNOWN'

        try {
            // 移除查询参数和锚点
            const cleanUrl = url.split('?')[0].split('#')[0]
            // 获取文件扩展名
            const extension = cleanUrl.split('.').pop()?.toLowerCase()

            if (!extension) return 'UNKNOWN'

            // 处理特殊情况
            const formatMap = {
                'gltf': 'GLTF',
                'glb': 'GLB',
                'obj': 'OBJ',
                'fbx': 'FBX',
                'stl': 'STL',
                'usdz': 'USDZ',
                'zip': 'ZIP',
                'ply': 'PLY',
                'dae': 'DAE',
                'x3d': 'X3D'
            }

            return formatMap[extension] || extension.toUpperCase()
        } catch (error) {
            console.warn('提取格式失败:', error, url)
            return 'UNKNOWN'
        }
    }

    /**
     * 选择最佳格式的模型文件
     * @param {Array} files - 可用的文件列表
     * @returns {Object|null} 最佳格式的文件对象
     */
    const selectBestFormatFile = (files) => {
        if (!files || !Array.isArray(files) || files.length === 0) {
            console.warn('[selectBestFormatFile] 没有可用的文件')
            return null
        }

        console.log('[selectBestFormatFile] 分析可用文件:', files.length, '个')

        // 为每个文件添加格式信息和优先级分数
        const filesWithPriority = files.map(file => {
            const format = extractFormatFromUrl(file.Url || file.url)
            const priority = MODEL_FORMAT_PRIORITY[format] || 0

            return {
                ...file,
                detectedFormat: format,
                priority: priority,
                originalUrl: file.Url || file.url
            }
        }).filter(file => file.originalUrl) // 过滤掉没有URL的文件

        if (filesWithPriority.length === 0) {
            console.warn('[selectBestFormatFile] 没有有效的文件URL')
            return null
        }

        // 按优先级排序（降序），GLB会排在最前面
        filesWithPriority.sort((a, b) => b.priority - a.priority)

        const selectedFile = filesWithPriority[0]

        console.log('[selectBestFormatFile] 文件优先级排序结果:', filesWithPriority.map(f => ({
            format: f.detectedFormat,
            priority: f.priority,
            url: f.originalUrl.substring(0, 50) + '...'
        })))

        console.log('[selectBestFormatFile] 选择的格式:', selectedFile.detectedFormat,
            '优先级:', selectedFile.priority)

        // 如果选择了GLB格式，特别记录
        if (selectedFile.detectedFormat === 'GLB') {
            console.log('🎯 [selectBestFormatFile] 成功选择GLB格式文件')
        }

        return selectedFile
    }

    /**
     * 分析文件格式分布
     * @param {Array} files - 文件列表
     * @returns {Object} 格式分析结果
     */
    const analyzeFileFormats = (files) => {
        const analysis = {
            total: files?.length || 0,
            formats: {},
            hasGLB: false,
            hasPriorityFormat: false,
            bestFormat: null,
            bestPriority: 0
        }

        if (!files || !Array.isArray(files)) return analysis

        files.forEach(file => {
            const format = extractFormatFromUrl(file.Url || file.url)
            const priority = MODEL_FORMAT_PRIORITY[format] || 0

            // 统计格式分布
            analysis.formats[format] = (analysis.formats[format] || 0) + 1

            // 检查是否有GLB
            if (format === 'GLB') {
                analysis.hasGLB = true
            }

            // 检查是否有高优先级格式（优先级 >= 8）
            if (priority >= 8) {
                analysis.hasPriorityFormat = true
            }

            // 记录最佳格式
            if (priority > analysis.bestPriority) {
                analysis.bestFormat = format
                analysis.bestPriority = priority
            }
        })

        return analysis
    }

    // ========== 原有的数据转换方法 ==========
    const transformHistoryData = (apiRecords) => {
        return apiRecords.map((record, index) => {
            const generateName = () => {
                if (record.generationMethod === 'prompt' && record.prompt) {
                    const trimmedPrompt = record.prompt.trim()
                    if (trimmedPrompt.length > 20) {
                        return `${trimmedPrompt.substring(0, 20)}...`
                    }
                    return trimmedPrompt
                } else if (record.generationMethod === 'image') {
                    return `图生3D模型 #${record.id}`
                } else if (record.generationMethod === 'prompt') {
                    return `文生3D模型 #${record.id}`
                } else {
                    return `3D模型 #${record.id}`
                }
            }

            const transformStatus = (status) => {
                const statusMap = {
                    'FINISHED': 'completed',
                    'RUN': 'processing',
                    'PROCESSING': 'processing',
                    'SUBMITTED': 'pending',
                    'WAIT': 'pending',
                    'FAILED': 'failed',
                    'FAIL': 'failed',
                    'ERROR': 'failed'
                }
                return statusMap[status] || 'pending'
            }

            const transformType = (method) => {
                const typeMap = {
                    'prompt': 'text',
                    'image': 'image'
                }
                return typeMap[method] || 'image'
            }

            const inferFormat = (url) => {
                if (!url) return 'glb'
                try {
                    const format = extractFormatFromUrl(url).toLowerCase()
                    return format === 'unknown' ? 'glb' : format
                } catch (error) {
                    console.warn('推断模型格式失败:', error)
                    return 'glb'
                }
            }

            const estimateFileSize = () => {
                if (!record.model3dUrl) return 0
                const baseSize = 1024 * 1024
                const randomFactor = Math.random() * 4 + 1
                return Math.floor(baseSize * randomFactor)
            }

            const generateCreateTime = () => {
                try {
                    const baseTimestamp = Date.now()
                    const timeOffset = (Math.max(...apiRecords.map(r => r.id)) - record.id) * 5 * 60 * 1000
                    const recordTime = new Date(baseTimestamp - timeOffset)
                    return recordTime.toLocaleString('zh-CN', {
                        year: 'numeric',
                        month: '2-digit',
                        day: '2-digit',
                        hour: '2-digit',
                        minute: '2-digit'
                    })
                } catch (error) {
                    const randomHoursAgo = Math.random() * 24 * 7
                    const randomTime = new Date(Date.now() - randomHoursAgo * 60 * 60 * 1000)
                    return randomTime.toLocaleString('zh-CN', {
                        year: 'numeric',
                        month: '2-digit',
                        day: '2-digit',
                        hour: '2-digit',
                        minute: '2-digit'
                    })
                }
            }

            const safeConvertToProxyUrl = (url) => {
                if (!url || typeof url !== 'string') return null
                try {
                    return convertToProxyUrl(url)
                } catch (error) {
                    console.warn('URL代理转换失败:', error, url)
                    return url
                }
            }

            const estimateFaceCount = () => {
                if (!record.model3dUrl) return '未知'
                const faceCountOptions = ['5万', '10万', '15万', '20万', '25万']
                const randomIndex = Math.floor(Math.random() * faceCountOptions.length)
                return faceCountOptions[randomIndex]
            }

            return {
                id: record.id.toString(),
                name: generateName(),
                type: transformType(record.generationMethod),
                status: transformStatus(record.status),
                createTime: generateCreateTime(),
                faces: estimateFaceCount(),
                fileSize: estimateFileSize(),
                thumbnail: safeConvertToProxyUrl(record.imageUrl),
                isStarred: false,
                downloadUrl: safeConvertToProxyUrl(record.model3dUrl),
                format: inferFormat(record.model3dUrl),
                originalData: record,
                availableFormats: record.model3dUrl ? [{
                    type: inferFormat(record.model3dUrl).toUpperCase(),
                    url: safeConvertToProxyUrl(record.model3dUrl),
                    originalUrl: record.model3dUrl,
                    previewUrl: safeConvertToProxyUrl(record.imageUrl)
                }] : [],
                selectedFormat: record.model3dUrl ? inferFormat(record.model3dUrl).toUpperCase() : 'GLB'
            }
        })
    }

    // ========== 新增：并发轮询核心方法 ==========

    /**
     * 查询任务状态API
     * @param {string} taskId - 任务ID
     * @param {string} requestId - 请求ID
     * @returns {Promise} API响应
     */
    const queryTaskStatus = async (taskId, requestId) => {
        try {
            console.log(`[ConcurrentPolling] 查询任务状态: taskId=${taskId}, requestId=${requestId}`)

            // 修正：使用params传递requestId参数，与useGenerator.js保持一致
            const response = await request.get(`/api/v2/task/status/${taskId}`, {
                requestId
            })
            return response
        } catch (error) {
            console.error(`查询任务状态失败 taskId: ${taskId}, requestId: ${requestId}`, error)
            throw error
        }
    }

    /**
     * 更新生成记录到后端
     * @param {Object} updateData - 更新数据
     * @returns {Promise} 更新结果
     */
    const updateGenerationRecord = async (updateData) => {
        try {
            console.log('[ConcurrentPolling] 更新生成记录:', updateData)

            const response = await postUpdateRecord([{
                model3dUrl: updateData.model3dUrl,
                requestId: updateData.requestId, // 确保使用requestId而不是taskId
                status: updateData.status || 'FINISHED'
            }])

            console.log('[ConcurrentPolling] 记录更新成功:', response)
            return response
        } catch (error) {
            console.error('[ConcurrentPolling] 更新生成记录失败:', error)
            throw error
        }
    }

    /**
     * 启动单个任务的轮询
     * @param {Object} task - 任务信息
     */
    const startTaskPolling = async (task) => {
        const { taskId, requestId, id: recordId } = task.originalData

        if (!taskId || !requestId) {
            console.warn(`[ConcurrentPolling] 任务缺少必要参数: taskId=${taskId}, requestId=${requestId}`)
            return
        }

        if (pollingState.activePolls.has(taskId)) {
            console.log(`[ConcurrentPolling] 任务 ${taskId} 已在轮询中`)
            return
        }

        const pollInfo = {
            taskId,
            requestId,
            recordId,
            attempts: 0,
            startTime: Date.now(),
            timer: null,
            isActive: true
        }

        pollingState.activePolls.set(taskId, pollInfo)
        console.log(`[ConcurrentPolling] 开始轮询任务: ${taskId}, requestId: ${requestId}`)

        // 执行轮询
        await pollTaskStatus(taskId)
    }

    /**
     * 轮询单个任务状态
     * @param {string} taskId - 任务ID
     */
    const pollTaskStatus = async (taskId) => {
        const pollInfo = pollingState.activePolls.get(taskId)
        if (!pollInfo || !pollInfo.isActive) {
            return
        }

        try {
            pollInfo.attempts++
            console.log(`[ConcurrentPolling] 轮询任务 ${taskId}, 第 ${pollInfo.attempts} 次尝试`)

            // 检查最大尝试次数
            if (pollInfo.attempts > pollingState.pollingConfig.maxAttempts) {
                throw new Error(`任务 ${taskId} 轮询超时`)
            }

            // 修正：传递taskId和requestId两个参数
            const response = await queryTaskStatus(taskId, pollInfo.requestId)
            const taskStatus = response.data?.Status

            console.log(`[ConcurrentPolling] 任务 ${taskId} 状态: ${taskStatus}`)

            if (taskStatus === 'DONE') {
                // 任务完成，处理结果
                await handleTaskCompletion(taskId, response.data)
            } else if (taskStatus === 'FAILED' || taskStatus === 'ERROR') {
                // 任务失败
                await handleTaskFailure(taskId, `任务执行失败: ${taskStatus}`)
            } else {
                // 继续轮询
                scheduleNextPoll(taskId)
            }

        } catch (error) {
            console.error(`[ConcurrentPolling] 轮询任务 ${taskId} 出错:`, error)
            await handleTaskFailure(taskId, error.message)
        }
    }

    /**
     * 处理任务完成 - 优先保存GLB格式
     * @param {string} taskId - 任务ID
     * @param {Object} taskData - 任务数据
     */
    const handleTaskCompletion = async (taskId, taskData) => {
        console.log(`[ConcurrentPolling] 任务 ${taskId} 完成`)

        try {
            const pollInfo = pollingState.activePolls.get(taskId)
            if (!pollInfo) return

            // 检查是否有3D模型文件
            if (!taskData.ResultFile3Ds || taskData.ResultFile3Ds.length === 0) {
                throw new Error('未找到生成的3D模型文件')
            }

            console.log(`[ConcurrentPolling] 任务 ${taskId} 包含 ${taskData.ResultFile3Ds.length} 个文件`)

            // 分析可用文件格式
            const formatAnalysis = analyzeFileFormats(taskData.ResultFile3Ds)
            console.log(`[ConcurrentPolling] 任务 ${taskId} 格式分析:`, formatAnalysis)

            // 使用新的文件选择逻辑，优先选择GLB格式
            const selectedFile = selectBestFormatFile(taskData.ResultFile3Ds)

            if (!selectedFile) {
                throw new Error('无法选择合适的模型文件')
            }

            const modelUrl = selectedFile.originalUrl || selectedFile.Url

            if (!modelUrl) {
                throw new Error('选中的文件没有有效的URL')
            }

            // 记录选择结果
            console.log(`[ConcurrentPolling] 任务 ${taskId} 最终选择:`, {
                格式: selectedFile.detectedFormat,
                优先级: selectedFile.priority,
                URL: modelUrl.substring(0, 100) + '...',
                是否GLB: selectedFile.detectedFormat === 'GLB'
            })

            // 更新生成记录到后端
            await updateGenerationRecord({
                model3dUrl: modelUrl,
                taskId: taskId,
                requestId: pollInfo.requestId,
                status: 'FINISHED',
                selectedFormat: selectedFile.detectedFormat
            })

            // 标记任务完成
            pollInfo.isActive = false
            pollingState.pendingUpdates.add(taskId)

            // 清理定时器
            if (pollInfo.timer) {
                clearTimeout(pollInfo.timer)
                pollInfo.timer = null
            }

            // 触发批量更新
            scheduleBatchUpdate()

            // 根据选择的格式显示不同的成功消息
            const formatEmoji = selectedFile.detectedFormat === 'GLB' ? '🎯' : '📁'
            ElMessage.success(`3D模型生成完成 ${formatEmoji} ${selectedFile.detectedFormat}: 任务 ${taskId}`)

        } catch (error) {
            console.error(`[ConcurrentPolling] 处理任务完成失败 ${taskId}:`, error)
            await handleTaskFailure(taskId, error.message)
        }
    }

    /**
     * 处理任务失败
     * @param {string} taskId - 任务ID
     * @param {string} errorMessage - 错误信息
     */
    const handleTaskFailure = async (taskId, errorMessage) => {
        console.error(`[ConcurrentPolling] 任务 ${taskId} 失败: ${errorMessage}`)

        const pollInfo = pollingState.activePolls.get(taskId)
        if (pollInfo) {
            pollInfo.isActive = false
            if (pollInfo.timer) {
                clearTimeout(pollInfo.timer)
                pollInfo.timer = null
            }
        }

        // 修正：更新失败状态时也使用正确的requestId
        try {
            await updateGenerationRecord({
                model3dUrl: null,
                taskId: taskId,
                requestId: pollInfo ? pollInfo.requestId : taskId, // 使用存储的requestId
                status: 'FAILED'
            })
        } catch (updateError) {
            console.error(`[ConcurrentPolling] 更新失败状态出错:`, updateError)
        }

        pollingState.pendingUpdates.add(taskId)
        scheduleBatchUpdate()

        ElMessage.error(`任务生成失败: ${taskId}`)
    }

    /**
     * 安排下次轮询
     * @param {string} taskId - 任务ID
     */
    const scheduleNextPoll = (taskId) => {
        const pollInfo = pollingState.activePolls.get(taskId)
        if (!pollInfo || !pollInfo.isActive) return

        pollInfo.timer = setTimeout(() => {
            pollTaskStatus(taskId)
        }, pollingState.pollingConfig.interval)
    }

    /**
     * 安排批量更新历史记录
     */
    const scheduleBatchUpdate = () => {
        if (pollingState.updateTimer) {
            clearTimeout(pollingState.updateTimer)
        }

        pollingState.updateTimer = setTimeout(async () => {
            if (pollingState.pendingUpdates.size > 0) {
                console.log(`[ConcurrentPolling] 批量更新历史记录，待更新任务数: ${pollingState.pendingUpdates.size}`)

                // 刷新历史记录
                await refreshHistory()

                // 清理已完成的轮询
                pollingState.pendingUpdates.forEach(taskId => {
                    pollingState.activePolls.delete(taskId)
                })
                pollingState.pendingUpdates.clear()

                console.log('[ConcurrentPolling] 历史记录更新完成')
            }
        }, pollingState.pollingConfig.batchUpdateDelay)
    }

    /**
     * 停止指定任务的轮询
     * @param {string} taskId - 任务ID
     */
    const stopTaskPolling = (taskId) => {
        const pollInfo = pollingState.activePolls.get(taskId)
        if (pollInfo) {
            pollInfo.isActive = false
            if (pollInfo.timer) {
                clearTimeout(pollInfo.timer)
                pollInfo.timer = null
            }
            pollingState.activePolls.delete(taskId)
            console.log(`[ConcurrentPolling] 停止轮询任务: ${taskId}`)
        }
    }

    /**
     * 停止所有轮询
     */
    const stopAllPolling = () => {
        console.log('[ConcurrentPolling] 停止所有轮询')

        pollingState.activePolls.forEach((pollInfo, taskId) => {
            if (pollInfo.timer) {
                clearTimeout(pollInfo.timer)
            }
        })

        pollingState.activePolls.clear()

        if (pollingState.updateTimer) {
            clearTimeout(pollingState.updateTimer)
            pollingState.updateTimer = null
        }

        pollingState.pendingUpdates.clear()
    }

    /**
     * 启动处理中任务的并发轮询
     * @param {Array} processingTasks - 处理中的任务列表
     */
    const startConcurrentPolling = async (processingTasks = []) => {
        console.log(`[ConcurrentPolling] 启动并发轮询，处理中任务数: ${processingTasks.length}`)

        for (const task of processingTasks) {
            if (task.status === 'processing' && task.originalData?.taskId && task.originalData?.requestId) {
                await startTaskPolling(task)
            }
        }
    }

    /**
     * 从历史记录中提取处理中的任务并启动轮询
     */
    const resumeProcessingTasks = async () => {
        const processingTasks = historyList.value.filter(
            task => task.status === 'processing' &&
                task.originalData?.taskId &&
                task.originalData?.requestId // 确保同时有taskId和requestId
        )

        console.log(`[ConcurrentPolling] 发现 ${processingTasks.length} 个处理中的任务`)

        if (processingTasks.length > 0) {
            // 打印任务详情用于调试
            processingTasks.forEach(task => {
                console.log(`[ConcurrentPolling] 处理中任务: id=${task.originalData.id}, taskId=${task.originalData.taskId}, requestId=${task.originalData.requestId}`)
            })

            await startConcurrentPolling(processingTasks)
        }
    }

    // ========== 原有方法（保持不变） ==========
    const fetchHistoryRecords = async (page = 1, pageSize = 20, append = false) => {
        try {
            historyState.loading = true
            historyState.error = null

            console.log('[useModelHistory] 获取历史记录:', { page, pageSize, append })

            const response = await getDataByPage({
                page: page,
                pageSize: pageSize
            })

            console.log('[useModelHistory] 历史记录响应:', response)

            if (!response) {
                throw new Error('接口无响应')
            }

            let responseData
            if (response.data) {
                responseData = response.data
            } else if (response.code === 1 && response.data) {
                responseData = response.data
            } else {
                responseData = response
            }

            const { total, records } = responseData

            if (!Array.isArray(records)) {
                throw new Error('返回的records不是数组格式')
            }

            const transformedRecords = transformHistoryData(records)

            if (append) {
                const existingIds = new Set(historyList.value.map(item => item.id))
                const newRecords = transformedRecords.filter(record => !existingIds.has(record.id))
                historyList.value = [...historyList.value, ...newRecords]
            } else {
                historyList.value = transformedRecords
            }

            historyState.total = total || 0
            historyState.currentPage = page
            historyState.hasMore = historyList.value.length < historyState.total

            console.log('[useModelHistory] 历史记录加载完成:', {
                total: historyState.total,
                loaded: historyList.value.length,
                hasMore: historyState.hasMore,
                newRecords: append ? transformedRecords.length : '刷新'
            })

            // 加载完成后启动处理中任务的轮询
            if (!append) {
                await resumeProcessingTasks()
            }

            return {
                success: true,
                total: historyState.total,
                records: transformedRecords
            }

        } catch (error) {
            console.error('[useModelHistory] 获取历史记录失败:', error)
            historyState.error = error.message
            const errorMessage = error.message.includes('网络') ? '网络连接失败，请检查网络' : `获取历史记录失败：${error.message}`
            ElMessage.error(errorMessage)
            return {
                success: false,
                error: error.message
            }
        } finally {
            historyState.loading = false
        }
    }

    const refreshHistory = async () => {
        console.log('[useModelHistory] 刷新历史记录')
        const result = await fetchHistoryRecords(1, historyState.pageSize, false)
        if (result.success) {
            ElMessage.success('历史记录已刷新')
        }
    }

    const loadMoreHistory = async () => {
        if (historyState.loading || !historyState.hasMore) {
            console.log('[useModelHistory] 无法加载更多:', { loading: historyState.loading, hasMore: historyState.hasMore })
            return
        }

        const nextPage = historyState.currentPage + 1
        console.log('[useModelHistory] 加载更多历史记录，页码:', nextPage)
        await fetchHistoryRecords(nextPage, historyState.pageSize, true)
    }

    const initializeHistory = async () => {
        console.log('[useModelHistory] 初始化历史记录')
        await fetchHistoryRecords(1, historyState.pageSize, false)
    }

    const setFilters = (filters) => {
        Object.assign(filterState, filters)
        console.log('[useModelHistory] 筛选条件已更新:', filterState)
    }

    const setSortBy = (sortBy) => {
        filterState.sortBy = sortBy
        console.log('[useModelHistory] 排序方式已更新:', sortBy)
    }

    const deleteHistoryRecord = async (recordId) => {
        try {
            console.log('[useModelHistory] 删除历史记录:', recordId)
            const index = historyList.value.findIndex(item => item.id === recordId)
            if (index > -1) {
                historyList.value.splice(index, 1)
                historyState.total = Math.max(0, historyState.total - 1)
                historyState.hasMore = historyList.value.length < historyState.total
            }
            ElMessage.success('记录已删除')
            return { success: true }
        } catch (error) {
            console.error('[useModelHistory] 删除记录失败:', error)
            ElMessage.error('删除失败：' + error.message)
            return { success: false, error: error.message }
        }
    }

    const updateStarStatus = async (recordId, isStarred) => {
        try {
            console.log('[useModelHistory] 更新收藏状态:', { recordId, isStarred })
            const record = historyList.value.find(item => item.id === recordId)
            if (record) {
                record.isStarred = isStarred
            }
            return { success: true }
        } catch (error) {
            console.error('[useModelHistory] 更新收藏状态失败:', error)
            ElMessage.error('操作失败：' + error.message)
            return { success: false, error: error.message }
        }
    }

    const findRecordById = (recordId) => {
        return historyList.value.find(record => record.id === recordId) || null
    }

    const addNewRecord = (newRecord) => {
        const transformedRecord = transformHistoryData([newRecord])[0]
        historyList.value.unshift(transformedRecord)
        historyState.total += 1
        console.log('[useModelHistory] 添加新记录:', transformedRecord.name)
    }

    // ========== 计算属性 ==========
    const filteredHistory = computed(() => {
        let filtered = historyList.value

        if (filterState.type !== 'all') {
            filtered = filtered.filter(item => item.type === filterState.type)
        }

        if (filterState.status !== 'all') {
            filtered = filtered.filter(item => item.status === filterState.status)
        }

        filtered = [...filtered].sort((a, b) => {
            switch (filterState.sortBy) {
                case 'time_desc':
                    return new Date(b.createTime) - new Date(a.createTime)
                case 'time_asc':
                    return new Date(a.createTime) - new Date(b.createTime)
                case 'name':
                    return a.name.localeCompare(b.name, 'zh-CN')
                default:
                    return 0
            }
        })

        return filtered
    })

    const totalSize = computed(() => {
        return historyList.value.reduce((total, item) => total + (item.fileSize || 0), 0)
    })

    const statusStats = computed(() => {
        const stats = {
            total: historyList.value.length,
            completed: 0,
            processing: 0,
            failed: 0,
            pending: 0
        }

        historyList.value.forEach(record => {
            if (stats.hasOwnProperty(record.status)) {
                stats[record.status]++
            }
        })

        return stats
    })

    const typeStats = computed(() => {
        const stats = {
            total: historyList.value.length,
            text: 0,
            image: 0
        }

        historyList.value.forEach(record => {
            if (stats.hasOwnProperty(record.type)) {
                stats[record.type]++
            }
        })

        return stats
    })

    // 新增：活跃轮询任务数计算属性
    const activePollingCount = computed(() => {
        return Array.from(pollingState.activePolls.values()).filter(poll => poll.isActive).length
    })

    // ========== 工具方法 ==========
    const formatFileSize = (bytes) => {
        if (bytes === 0) return '0 B'
        const k = 1024
        const sizes = ['B', 'KB', 'MB', 'GB']
        const i = Math.floor(Math.log(bytes) / Math.log(k))
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    }

    const getStatusTagType = (status) => {
        const types = {
            pending: 'warning',
            processing: 'primary',
            completed: 'success',
            failed: 'danger'
        }
        return types[status] || ''
    }

    const getStatusLabel = (status) => {
        const labels = {
            pending: '等待中',
            processing: '处理中',
            completed: '已完成',
            failed: '失败'
        }
        return labels[status] || '未知'
    }

    const getTypeLabel = (type) => {
        const labels = {
            text: '文生3D',
            image: '图生3D',
            all: '全部'
        }
        return labels[type] || type
    }

    const getStatusColor = (status) => {
        const colors = {
            pending: 'bg-yellow-500',
            processing: 'bg-blue-500',
            completed: 'bg-green-500',
            failed: 'bg-red-500'
        }
        return colors[status] || 'bg-gray-500'
    }

    const getTypeColor = (type) => {
        const colors = {
            text: 'text-blue-400',
            image: 'text-green-400'
        }
        return colors[type] || 'text-gray-400'
    }

    // ========== 清理方法 ==========
    const cleanup = () => {
        stopAllPolling()
        console.log('useModelHistory 清理完成')
    }

    // ========== 返回接口 ==========
    return {
        // 响应式数据
        historyList,
        historyState,
        filterState,
        pollingState, // 新增

        // 计算属性
        filteredHistory,
        totalSize,
        statusStats,
        typeStats,
        activePollingCount, // 新增

        // 核心方法
        fetchHistoryRecords,
        refreshHistory,
        loadMoreHistory,
        initializeHistory,

        // 操作方法
        setFilters,
        setSortBy,
        deleteHistoryRecord,
        updateStarStatus,
        findRecordById,
        addNewRecord,

        // 新增：并发轮询方法
        startConcurrentPolling,
        resumeProcessingTasks,
        stopTaskPolling,
        stopAllPolling,
        queryTaskStatus,
        updateGenerationRecord,

        // 新增：格式相关的工具方法
        getFormatPriority: () => ({ ...MODEL_FORMAT_PRIORITY }),
        analyzeFileFormats,
        extractFormatFromUrl,
        selectBestFormatFile,

        // 工具方法
        transformHistoryData,
        formatFileSize,
        getStatusTagType,
        getStatusLabel,
        getTypeLabel,
        getStatusColor,
        getTypeColor,

        // 清理方法
        cleanup
    }
}